<template>
  <h-drawer
    v-model="visible"
    :width="1200"
    :loading="
      saveLoading ||
      getWarehouseLoading ||
      getSparePartInfoBeforeCheckLoading ||
      getSparePartListBeforeCheckLoading
    "
    :title="props.applyType === 'backup-machine' ? '申请备用机' : '申请配件'"
    unit="px"
    @close="onCancel"
  >
    <div class="body">
      <div class="form_container">
        <div class="title"> 基本信息 </div>
        <div class="form">
          <el-form label-position="top">
            <div class="form_content">
              <div v-if="props.applyType === 'spare-part'" class="form_item">
                <!-- 申请类型 -->
                <el-form-item label="申请类型">
                  <el-select
                    v-model="tableDataList.type"
                    clearable
                    placeholder="申请类型"
                    @change="handleChangeType"
                  >
                    <el-option label="公司配件" :value="1" />
                    <el-option label="外部配件" :value="2" />
                  </el-select>
                </el-form-item>

                <!-- 部门配件类型 -->
                <el-form-item v-if="tableDataList.type === 2" label="部门配件类型">
                  <el-select
                    v-model="tableDataList.networkSpareType"
                    clearable
                    placeholder="部门配件类型"
                    :disabled="tableDataList.type !== 2"
                    @change="handleChangeNetworkSpareType"
                  >
                    <el-option label="部门仓" :value="1" />
                    <el-option label="自购备件" :value="3" />
                  </el-select>
                </el-form-item>

                <!-- 收货地址类型 -->
                <el-form-item label="收货地址类型">
                  <el-select
                    v-model="tableDataList.receiptAddrType"
                    clearable
                    placeholder="收货地址类型"
                    :disabled="tableDataList.type === 2"
                    @change="handleChangeAddressType"
                  >
                    <el-option label="工单客户地址" :value="1" />
                    <el-option label="部门地址" :value="2" />
                  </el-select>
                </el-form-item>
              </div>

              <div class="form_item">
                <!-- 收货人姓名 -->
                <el-form-item label="收货人姓名">
                  <el-input
                    v-model.trim="tableDataList.receiptName"
                    clearable
                    placeholder="收货人姓名"
                  />
                </el-form-item>

                <!-- 收货人手机号 -->
                <el-form-item label="收货人手机号">
                  <el-input
                    v-model.trim="tableDataList.receiptPhone"
                    clearable
                    maxlength="11"
                    placeholder="收货人手机号"
                    @keyup="(e: Event) => (e.target as HTMLInputElement).value = (e.target as HTMLInputElement).value.replace(/[^\d]/g, '')"
                  />
                </el-form-item>
              </div>

              <div class="form_item">
                <!-- 收货人地址 -->
                <el-form-item label="收货人地址">
                  <single-address
                    ref="singleAddressInstance"
                    :address="consigneeAddress"
                    class="single_address"
                  />
                </el-form-item>

                <!-- 详细地址 -->
                <el-form-item label="详细地址">
                  <el-input
                    v-model.trim="tableDataList.receiptAddress"
                    clearable
                    maxlength="200"
                    placeholder="收货人详细地址"
                    show-word-limit
                    size="small"
                    type="textarea"
                    resize="both"
                  />
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>
      </div>
      <div class="table">
        <el-table
          :border="true"
          :data="tableDataList.spareMaterialVos"
          resizable
          stripe
          :max-height="600"
        >
          <!-- 序号 -->
          <el-table-column :align="'center'" fixed="left" label="序号" width="50" type="index" />

          <!-- 结算类型 -->
          <el-table-column v-if="props.applyType === 'spare-part'" label="结算类型" width="120">
            <template #default="scope">
              <el-select
                v-model="scope.row.type"
                placeholder="结算类型"
                @change="handleChangeIncomeOrPayType(scope.$index)"
              >
                <el-option v-if="!userStore.isCurrentRoleNetwork" :value="1" label="公司承担" />
                <el-option v-if="!userStore.isCurrentRoleNetwork" :value="2" label="收取客户" />
                <el-option :value="3" label="支付部门" />
              </el-select>
            </template>
          </el-table-column>

          <!-- 配件编号 -->
          <el-table-column
            :label="props.applyType === 'spare-part' ? '配件编号' : '设备编号'"
            width="140"
          >
            <template #default="{ row, $index }">
              <el-popover
                placement="bottom-start"
                :width="700"
                :visible="row.popoverVisible"
                popper-style="padding: 0;"
                :show-arrow="false"
              >
                <template #reference>
                  <el-input
                    v-model.trim="row.code"
                    placeholder="请输入配件编号"
                    @input="(keyword: string) => handleSparePartCodeInput(keyword, $index)"
                    @blur="row.popoverVisible = false"
                  />
                </template>

                <el-table
                  v-loading="getSparePartOptionsLoading"
                  :border="true"
                  :data="sparePartOptions"
                  max-height="400"
                  @row-click="(row: OrderSparePartAPIResponse.SparePartOption) => handleSparePartOptionClick(row, $index)"
                >
                  <!-- 序号 -->
                  <el-table-column type="index" label="序号" :align="'center'" width="50" />

                  <!-- 物料编号 -->
                  <el-table-column prop="code" label="物料编号" width="140" />

                  <!-- 物料名称 -->
                  <el-table-column
                    show-overflow-tooltip
                    prop="name"
                    label="物料名称"
                    min-width="160"
                  />

                  <!-- 物料分类 -->
                  <el-table-column prop="type" label="物料分类" width="120" />
                </el-table>
              </el-popover>
            </template>
          </el-table-column>

          <!-- 配件名称 -->
          <el-table-column
            :label="props.applyType === 'spare-part' ? '配件名称' : '设备名称'"
            min-width="160"
          >
            <template #default="{ row }">
              <el-input :model-value="row.name" disabled />
            </template>
          </el-table-column>

          <!-- 合格证 -->
          <el-table-column v-if="props.applyType === 'backup-machine'" label="合格证" width="160">
            <template #default="{ row, $index }">
              <el-select
                v-model="row.snCode"
                placeholder="请选择合格证"
                :loading="getSnCodeOptionListLoading"
                filterable
                :filter-method="(keyword: string) => handleSnCodeOptionFilter(keyword, $index)"
              >
                <el-option
                  v-for="(snCodeOption, snCodeOptionIndex) in row.snCodeOptionList"
                  :key="snCodeOptionIndex"
                  :label="snCodeOption.securityCode"
                  :value="snCodeOption.securityCode"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- 规格 -->
          <el-table-column label="规格" width="140">
            <template #default="scope">
              <el-select
                v-model="scope.row.specId"
                :loading="loading2"
                placeholder="请选择"
                :disabled="!scope.row.spareId"
                @change="(id: string) => handleChangeSpec(id, scope.$index)"
              >
                <template #header>
                  <div class="select_header">
                    <el-input
                      v-model.trim="getSpecOptionsParam.name"
                      @keyup.enter="getSpecOptionsFn(scope.row.spareId, scope.$index)"
                    />
                    <h-plain-button @click="getSpecOptionsFn(scope.row.spareId, scope.$index)">
                      搜索
                    </h-plain-button>
                  </div>
                </template>
                <el-option
                  v-for="item in scope.row.partSpecOptions"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                  @click="handlePartSpecClick(item, scope.$index)"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- 质保状态 -->
          <el-table-column label="质保状态" width="100">
            <template #default="scope">
              <el-select
                v-model="scope.row.overinsured"
                filterable
                placeholder="质保状态"
                @change="handleChangeIncomeOrPayType(scope.$index)"
              >
                <el-option label="保内" :value="false" />
                <el-option label="保外" :value="true" />
              </el-select>
            </template>
          </el-table-column>

          <template v-if="props.applyType === 'spare-part'">
            <!-- 申请数量 -->
            <el-table-column label="申请数量" width="80">
              <template #default="{ row }">
                <el-input v-model.trim.number="row.qty" clearable placeholder="数量" />
              </template>
            </el-table-column>

            <!-- 公司承担费用-->
            <el-table-column label="公司承担费用" width="120">
              <template #default="{ row }">
                <el-input-number
                  v-model.trim.number="row.price"
                  style="width: 90px"
                  :controls="false"
                  clearable
                />
              </template>
            </el-table-column>

            <!-- 收取客户费用 -->
            <el-table-column label="收取客户费用" width="120">
              <template #default="{ row }">
                <el-input-number
                  v-model.trim="row.customerUndertakePrice"
                  style="width: 90px"
                  :controls="false"
                  clearable
                />
              </template>
            </el-table-column>

            <!-- 支付部门费用 -->
            <el-table-column label="支付部门费用" width="120">
              <template #default="{ row }">
                <el-input-number
                  v-model.trim="row.networkUndertakePrice"
                  style="width: 90px"
                  :controls="false"
                  clearable
                />
              </template>
            </el-table-column>

            <!-- 备注 -->
            <el-table-column label="备注" max-width="150" min-width="140">
              <template #default="scope">
                <el-input v-model.trim="scope.row.remark" clearable placeholder="填写备注" />
              </template>
            </el-table-column>

            <!-- 附件 -->
            <el-table-column label="附件(最多上传8个)" :width="annexColumnWidth">
              <template #default="scope">
                <div class="updata_pic">
                  <template v-for="(img, index) in scope.row.images" :key="index">
                    <h-image
                      :width="60"
                      :height="40"
                      :src="img.image"
                      :initial-index="index"
                      :preview-src-list="scope.row.images.map((item: SparePartFormTableItemImageRow) => item.image)"
                      fit="scale-down"
                      :padding="2"
                      :mask-btn-gap="3"
                      @del="handleDelFile(scope.$index, index)"
                    />
                  </template>
                  <h-image
                    v-if="scope.row.images.length < 8"
                    :width="60"
                    :height="37.5"
                    :src="uploadPlaceholderImg"
                    :padding="2"
                  >
                    <div style="line-height: 35.5px; height: 35.5px">
                      <el-upload
                        :auto-upload="false"
                        :on-change="(file: UploadFile) => handleUploadChange(file, scope.$index)"
                        :show-file-list="false"
                        accept="image/*"
                        action="#"
                        multiple
                      >
                        <i
                          class="iconfont icon-img-upload"
                          style="font-size: 24px; color: #fff"
                        ></i>
                      </el-upload>
                    </div>
                  </h-image>
                </div>
              </template>
            </el-table-column>
          </template>

          <!--操作-->
          <el-table-column
            v-if="props.applyType === 'spare-part'"
            fixed="right"
            label="操作"
            width="100"
          >
            <template #default="scope">
              <el-space :size="0" :spacer="spacer">
                <h-link
                  v-if="tableDataList.spareMaterialVos.length > 1"
                  type="error"
                  @click="deleteItem(scope.$index)"
                >
                  删除
                </h-link>
                <h-link v-if="scope.$index === 0" @click="addItem">添加</h-link>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <h-button is-modal type="primary" @click="onSaveBtn">提交申请</h-button>
      <h-button is-modal @click="onCancel">取消</h-button>
    </template>
  </h-drawer>
</template>

<script lang="ts" setup>
  import { h, nextTick, PropType, ref, watch } from 'vue'
  import { getOrderNetworkAddress, getWorkUserAddress, spareSaveOrder } from '@/api/parts'
  import { getOrderSparePageSelect, getOrderSpareSpecSelect } from '@/api/order'
  import { orderAnnexUpload } from '@/api/upload'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import { ElDivider, UploadFile, UploadRawFile } from 'element-plus'
  import _ from 'lodash'
  import uploadPlaceholderImg from '@/assets/image/avatar_upload_default.png'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { useGetNetworkWarehouse } from '@/services/pages/storage/useWarehouse'
  import { useGetOrderSparePartOptions } from '@/services/module/order/useSparePart'
  import { useUserStore } from '@/store/modules/user'
  import { SparePartFormTableItemImageRow, SparePartTableItem } from './types'
  import {
    useGetSnCodeOptionListBySparePartId,
    useGetOrderSparePartInfoBeforeCheck,
    useGetSparePartListByOrderSparePartId,
  } from '@/services/module/order/useSparePart'

  // interface PartOptions {
  //   brand: string
  //   brandId: string
  //   code: string
  //   id: string
  //   image: string
  //   itemNumber: string
  //   model: string
  //   name: string
  //   overPrice: null | number
  //   price: null | number
  //   select: boolean
  //   specSkuCode: null | string
  //   strs: null | string
  //   type: string
  //   typeId: string
  // }

  const {
    sparePartOptions,
    getSparePartOptionsParam,
    getSparePartOptionsLoading,
    getSparePartOptions,
  } = useGetOrderSparePartOptions()
  const { warehouse, getWarehouseLoading, getWarehouse } = useGetNetworkWarehouse()
  const {
    snCodeOptionList,
    getSnCodeOptionListParam,
    getSnCodeOptionListLoading,
    getSnCodeOptionList,
  } = useGetSnCodeOptionListBySparePartId()
  const {
    sparePartInfoBeforeCheck,
    getSparePartInfoBeforeCheckLoading,
    getSparePartInfoBeforeCheck,
  } = useGetOrderSparePartInfoBeforeCheck()
  const {
    sparePartListBeforeCheck,
    getSparePartListBeforeCheckLoading,
    getSparePartListBeforeCheck,
  } = useGetSparePartListByOrderSparePartId()

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
    applyType: {
      type: String as PropType<'spare-part' | 'backup-machine'>,
      default: () => 'spare-part',
    },
    sparePartId: {
      type: String,
      default: () => '',
    },
  })

  const emits = defineEmits<{
    (e: 'update-list'): void
  }>()

  // 客户状态管理
  const userStore = useUserStore()

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  // 附件列宽
  const annexColumnWidth = ref(130)

  // 设置附件列的宽度
  const setAnnexColumnWidth = () => {
    let maxImageLength = Math.max(
      ...tableDataList.value.spareMaterialVos.map((item) => item.images.length),
    )

    // 在图片数量小于8张时要把上传按钮的宽度计算进去
    if (maxImageLength < 8) {
      maxImageLength += 1
    }

    // 这是为了解决删剩一张图时，列宽会变得很小，导致标题会换行
    if (maxImageLength > 0) {
      annexColumnWidth.value = maxImageLength * 60 + (maxImageLength - 1) * 8 + 24
    }

    if (annexColumnWidth.value < 130) {
      annexColumnWidth.value = 130
    }
  }

  /**
   * 配件编号输入事件
   * @param {string} code - 输入的编号
   * @param {number} sparePartIndex - 配件索引
   */
  const handleSparePartCodeInput = _.debounce(async (code: string, sparePartIndex: number) => {
    const sparePart = tableDataList.value.spareMaterialVos[sparePartIndex]
    if (!sparePart) {
      return false
    }

    if (code) {
      tableDataList.value.spareMaterialVos[sparePartIndex].popoverVisible = true
      getSparePartOptionsParam.value.name = code
      await getSparePartOptions(props.orderDetail.id)
    }
  }, 500)

  /**
   * 配件下拉选项点击事件
   * @param {OrderSparePartAPIResponse.SparePartOption} sparePartOption - 配件下拉选项
   * @param {number} index - 配件索引
   */
  const handleSparePartOptionClick = async (
    sparePartOption: OrderSparePartAPIResponse.SparePartOption,
    index: number,
  ) => {
    tableDataList.value.spareMaterialVos[index].spareId = sparePartOption.id
    tableDataList.value.spareMaterialVos[index].specSku = ''
    tableDataList.value.spareMaterialVos[index].specName = ''
    tableDataList.value.spareMaterialVos[index].model = sparePartOption.model
    tableDataList.value.spareMaterialVos[index].name = sparePartOption.name
    tableDataList.value.spareMaterialVos[index].code = sparePartOption.code
    tableDataList.value.spareMaterialVos[index].price = 0
    tableDataList.value.spareMaterialVos[index].networkUndertakePrice = 0
    tableDataList.value.spareMaterialVos[index].customerUndertakePrice = 0
    if (sparePartOption.id) {
      await getSpecOptionsFn(sparePartOption.id, index)
      getSnCodeOptionListParam.value.spareId = sparePartOption.id
      await getSnCodeOptionList()
      tableDataList.value.spareMaterialVos[index].snCodeOptionList = snCodeOptionList.value
      if (tableDataList.value.spareMaterialVos[index].partSpecOptions) {
        const firstSparePartSpecOption =
          tableDataList.value.spareMaterialVos[index].partSpecOptions[0]
        tableDataList.value.spareMaterialVos[index].specId = firstSparePartSpecOption.id
        handlePartSpecClick(firstSparePartSpecOption, index)
      }
    }
  }

  /**
   * 获取费用详情
   * @param {number} index - 索引
   */
  const getSpareDetail = (index: number) => {
    return tableDataList.value.spareMaterialVos[index]
  }

  /**
   * 收支类型改变
   * @param {number} index - 操作的表格行的索引
   */
  const handleChangeIncomeOrPayType = (index: number) => {
    /**
     * 提取选择的规格的金额
     */
    let price = 0
    if (
      tableDataList.value.spareMaterialVos[index].partSpecOptions &&
      tableDataList.value.spareMaterialVos[index].specId
    ) {
      const feeProject = tableDataList.value.spareMaterialVos[index].partSpecOptions.find(
        (module) => module.id === tableDataList.value.spareMaterialVos[index].specId,
      )
      if (feeProject) {
        price = getSpareDetail(index).overinsured ? feeProject.overPrice : feeProject.price
      }
    }
    tableDataList.value.spareMaterialVos[index].customerUndertakePrice = 0
    tableDataList.value.spareMaterialVos[index].price = 0
    tableDataList.value.spareMaterialVos[index].networkUndertakePrice = 0
    if (getSpareDetail(index).type === 1) {
      tableDataList.value.spareMaterialVos[index].price = price
    } else if (getSpareDetail(index).type === 2) {
      tableDataList.value.spareMaterialVos[index].customerUndertakePrice = price
    } else if (getSpareDetail(index).type === 3) {
      tableDataList.value.spareMaterialVos[index].networkUndertakePrice = price
    }
  }
  // 弹窗的显示状态
  const visible = defineModel('modelValue', { type: Boolean, default: false })

  // 获取配件下拉选项关键字
  const getPartOptionsKeyword = ref('')

  // 配件下拉选项
  const partOptions = ref<Array<OrderSparePartAPIResponse.SparePartOption>>([])

  // 获取配件下拉选项方法
  const getPartOptionsFn = async () => {
    loading2.value = true
    const res = await getOrderSparePageSelect(
      { limit: 0, name: getPartOptionsKeyword.value, page: 0 },
      props.orderDetail.id,
    )
    if (res.data.code === 20000) {
      partOptions.value = res.data.data.rows
    } else {
      HMessageBox.error(res.data.message)
    }
    loading2.value = false
  }

  // 获取规格下拉选项请求参数
  const getSpecOptionsParam = ref({
    limit: 0,
    name: '',
    page: 0,
  })

  /**
   * 获取规格下拉选项方法
   * @param {string} id - 配件id
   * @param {number} index - 操作的表格行的索引
   */
  const getSpecOptionsFn = async (id: string, index: number) => {
    loading2.value = true
    const res = await getOrderSpareSpecSelect(getSpecOptionsParam.value, id)
    if (res.data.success) {
      tableDataList.value.spareMaterialVos[index].partSpecOptions = res.data.data.rows
    } else {
      HMessageBox.error(res.data.message)
    }
    loading2.value = false
  }

  const loading2 = ref(false)

  const tableDataList = ref<OrderSparePartAPIRequest.SparePartForm<SparePartTableItem>>({
    delSpareMaterialIds: [],
    id: '',
    networkSpareType: 1,
    receiptAddrType: 1,
    receiptAddress: '',
    receiptArea: '',
    receiptCity: '',
    receiptName: '',
    receiptPhone: '',
    receiptProvince: '',
    receiptTown: '',
    remark: '',
    spareMaterialVos: [
      {
        delImageIds: [],
        id: '',
        images: [],
        model: '',
        name: '',
        overinsured: true,
        networkUndertakePrice: 0,
        price: 0,
        qty: 1,
        customerUndertakePrice: 0,
        remark: '',
        spareId: '',
        specId: '',
        specName: '',
        specSku: '',
        type: userStore.isCurrentRoleNetwork ? 3 : 1,
        popoverVisible: false,
        applyDiscountPrice: 0,
        code: '',
        coreMaterials: false,
        discountPrice: 0,
        enableBatchNo: false,
        oldCopePositionId: '',
        oldCopeStoreId: '',
        oldCopeWay: 1,
        snCode: '',
        snCodes: [],
        workWarrantyCategoryId: '',
        snCodeOptionList: [],
      },
    ],
    type: 1,
    userOrNetworkId: '',
    workId: '',
    isStandby: 0,
    securityCode: '',
  })
  const singleAddressInstance = ref()
  const consigneeAddress = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })

  // 添加
  function addItem() {
    const item: SparePartTableItem = {
      delImageIds: [],
      id: '',
      images: [],
      model: '',
      name: '',
      overinsured: true,
      networkUndertakePrice: 0,
      price: 0,
      qty: 1,
      customerUndertakePrice: 0,
      remark: '',
      spareId: '',
      specId: '',
      specName: '',
      specSku: '',
      type: userStore.isCurrentRoleNetwork ? 3 : 1,
      popoverVisible: false,
      applyDiscountPrice: 0,
      code: '',
      coreMaterials: false,
      discountPrice: 0,
      enableBatchNo: false,
      oldCopePositionId: '',
      oldCopeStoreId: '',
      oldCopeWay: 1,
      snCode: '',
      snCodes: [],
      workWarrantyCategoryId: '',
      partSpecOptions: [],
      snCodeOptionList: [],
    }
    tableDataList.value.spareMaterialVos.push(item)

    if (
      tableDataList.value.type === 2 &&
      tableDataList.value.networkSpareType === 1 &&
      !warehouse.value.enableStore
    ) {
      HMessageBox.error('当前部门没有仓库不允许申请配件')
      return
    }
  }

  // 新增删除
  function deleteItem(n: number) {
    if (tableDataList.value.spareMaterialVos.length == 1) {
      return
    }
    tableDataList.value.spareMaterialVos = tableDataList.value.spareMaterialVos.filter(
      (o, index) => {
        return index != n
      },
    )
  }

  // 地址类型变化
  const handleChangeAddressType = (val: 1 | 2) => {
    singleAddressInstance.value.getSelectAddr()
    switch (val) {
      case 1:
        getWorkUserAddressData()
        break
      case 2:
        getOrderNetworkAddressData()
        break
      default:
        tableDataList.value.receiptName = ''
        tableDataList.value.receiptPhone = ''
        tableDataList.value.receiptAddress = ''
        tableDataList.value.receiptProvince = ''
        tableDataList.value.receiptCity = ''
        tableDataList.value.receiptArea = ''
        tableDataList.value.receiptTown = ''
        consigneeAddress.value = {
          province: '',
          city: '',
          area: '',
          town: '',
        }
        singleAddressInstance.value.clearSelectAddr()
        break
    }
  }

  /**
   * 获取用户地址
   */
  const getWorkUserAddressData = () => {
    getWorkUserAddress(props.orderDetail.id).then((res) => {
      if (res.data.success) {
        tableDataList.value.userOrNetworkId = res.data.data.row.id
        tableDataList.value.receiptName = res.data.data.row.name
        tableDataList.value.receiptPhone = res.data.data.row.phone
        tableDataList.value.receiptAddress = res.data.data.row.address
        tableDataList.value.receiptProvince = res.data.data.row.province
        tableDataList.value.receiptCity = res.data.data.row.city
        tableDataList.value.receiptArea = res.data.data.row.area
        tableDataList.value.receiptTown = res.data.data.row.town
        consigneeAddress.value = {
          province: tableDataList.value.receiptProvince,
          city: tableDataList.value.receiptCity,
          area: tableDataList.value.receiptArea,
          town: tableDataList.value.receiptTown,
        }
      } else {
        HMessageBox.error(res.data.message)
      }
    })
  }

  /**
   * 获取部门地址
   */
  const getOrderNetworkAddressData = () => {
    getOrderNetworkAddress(props.orderDetail.id).then((res) => {
      if (res.data.success) {
        tableDataList.value.userOrNetworkId = res.data.data.row.id
        tableDataList.value.receiptName = res.data.data.row.name
        tableDataList.value.receiptPhone = res.data.data.row.phone
        tableDataList.value.receiptAddress = res.data.data.row.address
        tableDataList.value.receiptProvince = res.data.data.row.province
        tableDataList.value.receiptCity = res.data.data.row.city
        tableDataList.value.receiptArea = res.data.data.row.area
        tableDataList.value.receiptTown = res.data.data.row.town
        consigneeAddress.value = {
          province: tableDataList.value.receiptProvince,
          city: tableDataList.value.receiptCity,
          area: tableDataList.value.receiptArea,
          town: tableDataList.value.receiptTown,
        }
      } else {
        HMessageBox.error(res.data.message)
      }
    })
  }

  /**
   * 规格变化
   * @param {string} id - 规格id
   * @param {number} index - 操作的表格行的索引
   */
  const handleChangeSpec = (id: string, index: number) => {
    if (!id) {
      tableDataList.value.spareMaterialVos[index].specSku = ''
      tableDataList.value.spareMaterialVos[index].specName = ''
      tableDataList.value.spareMaterialVos[index].price = 0
    }
  }

  /**
   * 配件点击事件
   * @param {object} val - 配件的信息
   * @param {number} index - 操作的表格行的索引
   */
  // const handlePartClick = (val: PartOptions, index: number) => {
  //   tableDataList.value.spareMaterialVos[index].model = val.model
  //   tableDataList.value.spareMaterialVos[index].name = val.name
  //   tableDataList.value.spareMaterialVos[index].price = 0
  //   tableDataList.value.spareMaterialVos[index].networkUndertakePrice = 0
  //   tableDataList.value.spareMaterialVos[index].customerUndertakePrice = 0
  // }

  /**
   * 配件规格点击事件
   * @param {object} val - 规格信息
   * @param {number} index - 操作的表格行的索引
   */
  const handlePartSpecClick = (val: OrderMaterialSpecOption, index: number) => {
    tableDataList.value.spareMaterialVos[index].specSku = val.specSkuCode
    tableDataList.value.spareMaterialVos[index].specName = val.name
    const price = getSpareDetail(index).overinsured ? val.overPrice : val.price
    tableDataList.value.spareMaterialVos[index].price = 0
    tableDataList.value.spareMaterialVos[index].networkUndertakePrice = 0
    tableDataList.value.spareMaterialVos[index].customerUndertakePrice = 0
    if (Number(price)) {
      if (getSpareDetail(index).type === 1) {
        tableDataList.value.spareMaterialVos[index].price = price
      }
      if (getSpareDetail(index).type === 2) {
        tableDataList.value.spareMaterialVos[index].customerUndertakePrice = price
      }
      if (getSpareDetail(index).type === 3) {
        tableDataList.value.spareMaterialVos[index].networkUndertakePrice = price
      }
    }
  }

  // 保存加载
  const saveLoading = ref(false)

  /**
   * 保存
   */
  async function onSaveBtn() {
    if (
      tableDataList.value.type === 2 &&
      tableDataList.value.networkSpareType === 1 &&
      !warehouse.value.enableStore
    ) {
      HMessageBox.error('当前部门没有仓库不允许申请配件')
      return
    }

    // if (!verifyPhone(tableDataList.value.receiptPhone)) {
    //   HMessageBox.error('手机号码格式不正确')
    //   return false
    // }
    saveLoading.value = true
    for (let i = 0; i < tableDataList.value.spareMaterialVos.length; i++) {
      const sparePart = tableDataList.value.spareMaterialVos[i]
      if (props.applyType === 'backup-machine' && !sparePart.snCode) {
        HMessageBox.error('请选择合格证')
        return
      }
    }

    for (const key in tableDataList.value.spareMaterialVos) {
      let sparePart = tableDataList.value.spareMaterialVos[key]
      let imageFileList: Array<UploadRawFile> = []
      if (sparePart.images.length > 0) {
        for (const i in sparePart.images) {
          if (sparePart.images[i].file) {
            imageFileList.push(sparePart.images[i].file)
          }
        }
        if (sparePart.images[0].file) {
          const res = await orderAnnexUpload(imageFileList)
          sparePart.images = res.data.data.rows.map((o) => ({
            id: '',
            image: o,
            file: null,
            type: 1,
          }))
        }
      }
    }
    const addr = singleAddressInstance.value.getSelectAddr()
    tableDataList.value.receiptProvince = addr.province
    tableDataList.value.receiptCity = addr.city
    tableDataList.value.receiptArea = addr.area
    tableDataList.value.receiptTown = addr.town
    if (tableDataList.value.type == 1) {
      tableDataList.value.networkSpareType = 1
    }
    tableDataList.value.workId = props.orderDetail.id
    tableDataList.value.spareMaterialVos = tableDataList.value.spareMaterialVos.map((item) => {
      const __item = _.cloneDeep(item)
      __item.status = 1
      delete __item.partSpecOptions
      delete __item.snCodeOptionList
      delete __item.popoverVisible
      return __item
    })
    if (props.sparePartId) {
      tableDataList.value.status = 1
    }
    const res = await spareSaveOrder(tableDataList.value)
    if (res.data.success) {
      HMessage.success('保存成功')
      emits('update-list')
      onCancel()
    } else {
      HMessageBox.error(res.data.message)
    }
    saveLoading.value = false
  }

  /**
   * 删除文件
   * @param {number} rowIndex - 操作的表格行的索引
   * @param {number} imgIndex - 文件索引
   */
  const handleDelFile = (rowIndex: number, imgIndex: number) => {
    const imgs = tableDataList.value.spareMaterialVos[rowIndex].images.splice(imgIndex, 1)
    tableDataList.value.spareMaterialVos[rowIndex].delImageIds.push(imgs[0].id)
    setAnnexColumnWidth()
  }

  /**
   * 添加图片事件
   * @param {object} file - 文件
   * @param {number} index - 操作的表格行的索引
   */
  const handleUploadChange = async (file: UploadFile, index: number) => {
    if (!file.raw) {
      return
    }

    if (!['image/png', 'image/jpg', 'image/jpeg'].includes(file.raw.type)) {
      HMessageBox.error('只能上传图片类型的文件')
      return
    }
    if (tableDataList.value.spareMaterialVos[index].images.length >= 8) {
      HMessageBox.error('最多上传8个')
      return
    }
    tableDataList.value.spareMaterialVos[index].images.push({
      image: URL.createObjectURL(file.raw),
      file: file.raw,
      id: '',
      type: 1,
    })
    setAnnexColumnWidth()
  }

  // 申请类型更新事件
  const handleChangeType = async () => {
    if (tableDataList.value.type === 2) {
      tableDataList.value.receiptAddrType = 1
      tableDataList.value.networkSpareType = 1
      await getWarehouse(props.orderDetail.networkId)
      if (!warehouse.value.enableStore) {
        HMessageBox.error('当前部门没有仓库不允许申请配件')
      }
    }
  }

  /**
   * 取消按钮事件
   */
  const onCancel = () => {
    tableDataList.value = {
      delSpareMaterialIds: [],
      id: '',
      networkSpareType: 1,
      receiptAddrType: 1,
      receiptAddress: '',
      receiptArea: '',
      receiptCity: '',
      receiptName: '',
      receiptPhone: '',
      receiptProvince: '',
      receiptTown: '',
      remark: '',
      spareMaterialVos: [
        {
          delImageIds: [],
          id: '',
          images: [],
          model: '',
          name: '',
          overinsured: true,
          networkUndertakePrice: 0,
          price: 0,
          qty: 1,
          customerUndertakePrice: 0,
          remark: '',
          spareId: '',
          specId: '',
          specName: '',
          specSku: '',
          type: userStore.isCurrentRoleNetwork ? 3 : 1,
          popoverVisible: false,
          applyDiscountPrice: 0,
          code: '',
          coreMaterials: false,
          discountPrice: 0,
          enableBatchNo: false,
          oldCopePositionId: '',
          oldCopeStoreId: '',
          oldCopeWay: 1,
          snCode: '',
          snCodes: [],
          workWarrantyCategoryId: '',
          snCodeOptionList: [],
        },
      ],
      type: 1,
      userOrNetworkId: '',
      workId: '',
      isStandby: 0,
      securityCode: '',
    }
    visible.value = false
  }

  /**
   * 部门配件类型更新事件
   * @param type - 配件类型
   */
  const handleChangeNetworkSpareType = async (type: 1 | 3) => {
    if (type === 1) {
      await getWarehouse(props.orderDetail.networkId)
      if (!warehouse.value.enableStore) {
        HMessageBox.error('当前部门没有仓库不允许申请配件')
      }
    }
  }

  /**
   * 序列号下拉选项筛选事件
   * @param keyword - 搜索关键字
   */
  const handleSnCodeOptionFilter = _.debounce((keyword: string, sparePartIndex: number) => {
    if (getSnCodeOptionListParam.value.code !== keyword) {
      getSnCodeOptionListParam.value.code = keyword
      getSnCodeOptionList().then(() => {
        tableDataList.value.spareMaterialVos[sparePartIndex].snCodeOptionList =
          snCodeOptionList.value
      })
    }
  }, 500)

  /**
   * 获取配件审核前的信息
   */
  const getSparePartInfo = async () => {
    await getSparePartInfoBeforeCheck(props.sparePartId)
    tableDataList.value = {
      delSpareMaterialIds: [],
      id: sparePartInfoBeforeCheck.value.id,
      networkSpareType: sparePartInfoBeforeCheck.value.networkSpareType,
      receiptAddrType: sparePartInfoBeforeCheck.value.receiptAddrType,
      receiptAddress: sparePartInfoBeforeCheck.value.receiptAddress,
      receiptArea: sparePartInfoBeforeCheck.value.receiptArea,
      receiptCity: sparePartInfoBeforeCheck.value.receiptCity,
      receiptName: sparePartInfoBeforeCheck.value.receiptName,
      receiptPhone: sparePartInfoBeforeCheck.value.receiptPhone,
      receiptProvince: sparePartInfoBeforeCheck.value.receiptProvince,
      receiptTown: sparePartInfoBeforeCheck.value.receiptTown,
      remark: sparePartInfoBeforeCheck.value.applyRemark,
      spareMaterialVos: [],
      type: sparePartInfoBeforeCheck.value.type,
      userOrNetworkId: sparePartInfoBeforeCheck.value.userOrNetworkId,
      workId: props.orderDetail.id,
      isStandby: props.applyType === 'backup-machine' ? 1 : 0,
      securityCode: '',
    }
  }

  /**
   * 获取列表详情
   */
  const getList = async () => {
    const errorMsg = await getSparePartListBeforeCheck(props.sparePartId)
    if (errorMsg) {
      HMessageBox.error(errorMsg)
      return
    }

    tableDataList.value.spareMaterialVos = sparePartListBeforeCheck.value.map((result) => {
      const sparePart: SparePartTableItem = {
        popoverVisible: false,
        partSpecOptions: [],
        snCodeOptionList: [],
        id: result.id,
        networkUndertakePrice: result.networkUndertakePrice,
        overinsured: result.overinsured,
        price: result.price,
        qty: result.qty,
        remark: result.remark,
        spareId: result.spareId,
        specId: result.specId,
        type: result.type,
        workWarrantyCategoryId: result.workWarrantyCategoryId || '',
        applyDiscountPrice: result.applyDiscountPrice === null ? 0 : result.applyDiscountPrice,
        customerUndertakePrice:
          result.customerUndertakePrice === null ? 0 : result.customerUndertakePrice,
        delImageIds: [],
        discountPrice: result.discountPrice === null ? 0 : result.discountPrice,
        images: result.images.map((img) => {
          return {
            image: img,
            id: '',
            type: 1,
            file: null,
          }
        }),
        code: result.spareCode,
        coreMaterials: false,
        enableBatchNo: false,
        model: result.applySpareModel,
        name: result.spareName,
        oldCopePositionId: '',
        oldCopeStoreId: '',
        oldCopeWay: result.oldCopeWay === null ? 1 : result.oldCopeWay,
        snCode: result.snCode,
        snCodes: [],
        specName: '',
        specSku: '',
      }

      return sparePart
    })
    for (let i = 0; i < tableDataList.value.spareMaterialVos.length; i++) {
      const sparePart = tableDataList.value.spareMaterialVos[i]
      if (sparePart.spareId) {
        await getSpecOptionsFn(sparePart.spareId, i)
        getSnCodeOptionListParam.value.spareId = sparePart.spareId
        await getSnCodeOptionList()
        tableDataList.value.spareMaterialVos[i].snCodeOptionList = snCodeOptionList.value
        if (tableDataList.value.spareMaterialVos[i].partSpecOptions) {
          const firstSparePartSpecOption =
            tableDataList.value.spareMaterialVos[i].partSpecOptions[0]
          tableDataList.value.spareMaterialVos[i].specId = firstSparePartSpecOption.id
          handlePartSpecClick(firstSparePartSpecOption, i)
        }
      }
      //   if (sparePart.spareId) {
      //     await getSparePartOptionList(sparePart.spareId)
      //     if (sparePartOptionList.value.length > 0) {
      //       sparePartList.value[i].sparePartName = sparePartOptionList.value[0].name
      //     }
      //     await getPartSpecOptionsFn(sparePartList.value[i].spareId, i)
      //     await getSnCodeOptionList()
      //     sparePartList.value[i].snCodeOptionList = snCodeOptionList.value
      //   }
      //   if (sparePartInfoBeforeCheck.value.networkSpareType != 3) {
      //     await getstorePageSelect('', i)
      //   }
    }
    // setAnnexColumnWidth()
  }

  const init = async () => {
    if (props.sparePartId) {
      await getSparePartInfo()
      await getList()
    }
  }

  watch(visible, () => {
    nextTick(() => {
      getWorkUserAddressData()
      getPartOptionsFn()
    })

    init()

    switch (props.applyType) {
      case 'backup-machine':
        tableDataList.value.isStandby = 1
        break
      case 'spare-part':
        tableDataList.value.isStandby = 0
        break
    }
  })
</script>

<style lang="scss" scoped>
  :deep(.el-input__inner) {
    text-align: left;
  }

  .body {
    display: flex;
    flex-direction: column;
    height: 100%;
    row-gap: 24px;

    .form_container {
      display: flex;
      flex-direction: column;
      gap: 12px;

      .title {
        display: flex;
        gap: 5px;
        align-items: center;
        font-size: 14px;
        border-left: 3px solid #007cff;
        padding-left: 5px;
      }

      .form {
        padding: 0 9px;

        :deep(.el-form) {
          .form_content {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            row-gap: 12px;
            column-gap: 32px;

            .form_item {
              display: flex;
              flex-direction: column;
              row-gap: 12px;

              .el-form-item {
                margin: 0;
                width: 100%;

                .el-form-item__label {
                  margin-bottom: 3px;
                  height: 16px;
                  line-height: 16px;
                }

                .el-form-item__content {
                  .el-input {
                    .el-input__wrapper {
                      height: 26px !important;
                    }
                  }

                  .el-cascader {
                    min-width: 300px;
                  }

                  .el-textarea {
                    width: 100%;
                    .el-textarea__inner {
                      width: 100%;
                      height: 28px;
                      min-height: 28px !important;
                      max-height: 120px !important;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    .add_btn {
      padding: 30px 0 6px 0;
    }
  }

  .select_header {
    display: flex;
    column-gap: 5px;

    :deep(.el-input__wrapper) {
      height: 26px !important;
      font-size: 12px !important;
    }
  }

  :deep(.el-select__wrapper) {
    min-height: 28px !important;
    border-radius: 2px !important;
    font-size: 12px !important;
  }

  :deep(.el-input__wrapper) {
    height: 28px !important;
    font-size: 12px !important;
  }

  .title_container {
    height: 14px;
    margin-bottom: 8px;
    display: flex;

    .title_top {
      border-left: 2px solid #007cff;
      line-height: 14px;
      padding-left: 6px;
      display: inline-block;
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 14px;

    .el-cascader .el-input {
      width: 220px;
    }

    .item-input {
      width: 300px;
    }

    .item-input-phone {
      width: 180px;
    }

    .item-input_w {
      width: 390px;
    }

    .el-form-item__label {
      font-size: 12px;
    }
  }

  :deep(.el-form-item .el-cascader .el-input) {
    width: 100%;
  }

  .form_sction {
    display: flex;
    align-items: flex-start;
  }

  .operation {
    display: flex;
    justify-content: center;
    align-items: center;

    .icon {
      cursor: pointer;
      margin: 0 6px;

      &:hover {
        transform: scale(1.2);
      }
    }
  }

  :deep(.el-table td.el-table__cell) {
    .el-input {
      .el-input-group__prepend {
        padding: 0 2px;
      }
    }
  }

  .btn_save {
    width: 60px;
  }

  .btn_cancel {
    width: 60px;

    &:hover {
      border: 1px solid #e5e5e5;
      color: #999;
      background-color: #e5e5e5;
    }
  }

  .footer_remark {
    margin-top: 20px;

    .w_input {
      width: 600px;
      margin-left: 10px;
    }
  }

  :deep(.updata_pic) {
    display: flex;
    align-items: center;
    gap: 8px;

    .el-upload {
      &.el-upload--picture-card {
        width: 40px;
        height: 40px;
      }
    }

    .disf_ipc {
      display: flex;
      width: 40px;
      height: 40px;
      position: relative;
      margin-right: 6px;
      border: 1px solid #7f7f7f27;
      border-radius: 4px;
      box-sizing: border-box;
      overflow: hidden;

      .img {
        width: 100%;
        position: absolute;
        border-radius: 4px;
      }

      .item-actions {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        opacity: 0;
      }

      &:hover .item-actions {
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #7f7f7f9d;
        opacity: 1;
        border-radius: 4px;

        .item-preview {
          margin: 0 4px;
          cursor: pointer;

          &:hover {
            transform: scale(1.2);
          }
        }

        .item-delete {
          margin: 0 4px;
          cursor: pointer;

          &:hover {
            transform: scale(1.2);
          }
        }
      }
    }
  }
</style>
